package com.ly.core.web.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ly.core.util.AppUtil;
import com.ly.core.util.ContextUtil;
import com.ly.core.util.FileUtil;
import com.ly.oa.model.system.AppUser;
import com.ly.oa.model.system.FileAttach;
import com.ly.oa.service.system.FileAttachService;

public class FileUploadServlet extends HttpServlet{
	
	private FileAttachService fileAttachService=(FileAttachService)AppUtil.getBean("fileAttachService");
	
	private String uploadPath=""; // 上传文件的目录   
	private String tempPath=""; // 临时文件目录 
	
	private String fileCat="others";
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		try {
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 缓存大小
			factory.setSizeThreshold(4096);
			factory.setRepository(new File(tempPath));
			ServletFileUpload fu=new ServletFileUpload(factory);

	        List<FileItem> fileItems = fu.parseRequest(req); 
	        
	        for(FileItem fi:fileItems){
	        	if("file_cat".equals(fi.getFieldName())){
	        		fileCat=fi.getString();
	        		break;
	        	}
	        }
	        
	        System.out.println("filetype:"+fileCat);
	        
	        Iterator i = fileItems.iterator();
	        //目前处理每次只上传一个文件
	        while(i.hasNext()) {
	            FileItem fi = (FileItem)i.next();
	            if("file_cat".equals(fi.getFieldName())){
	            	continue;
	            }
	            
	            //返回文件名及路径及fileId.
	            String path = fi.getName();
	            System.out.println("path:" + path);
	            
		        int start=path.lastIndexOf("\\");
		        
		        //原文件名
		        String fileName=path.substring(start+1);
		        
		        String relativeFullPath=fileCat+"/" + FileUtil.generateFilename(fileName);
		        
		        int index=relativeFullPath.lastIndexOf("/");
		        
		        
		        File dirPath=new File(uploadPath+"/" + relativeFullPath.substring(0,index+1));
		        
		        if(!dirPath.exists()){
		        	dirPath.mkdirs();
		        }
		        
		        fi.write(new File(uploadPath+"/" + relativeFullPath));
		        
		        FileAttach file=new FileAttach();

		        file.setCreatetime(new Date());
		        AppUser curUser=ContextUtil.getCurrentUser();
		        if(curUser!=null){
		        	file.setCreator(curUser.getFullname());
		        }else{
		        	file.setCreator("UNKown");//TODO add the current user name here.
		        }
		        int dotIndex=fileName.indexOf(".");
		       
		        file.setExt(fileName.substring(dotIndex+1));
		       
		        file.setFileName(fileName);
		        
		        file.setFilePath(relativeFullPath);
		        
		        file.setFileType(fileCat);
		        
		        file.setNote(fi.getSize()+" bytes");
		        
		        fileAttachService.save(file);
		      
		        StringBuffer sb=new StringBuffer("{success:true");
		        sb.append(",fileId:").append(file.getFileId())
		        .append(",fileName:'").append(file.getFileName())
		        .append("',filePath:'").append(file.getFilePath()).append("',message:'upload file success.("+ fi.getSize()+" bytes)'");
		        sb.append("}");
		        
		        System.out.println("str:" + sb.toString());
		        
		        resp.getWriter().write(sb.toString());
	        }
	        
	    }    
	    catch(Exception e) {    
	    	System.out.println(e.getMessage()+" : "+e.getCause());
	    	resp.getWriter().write("{'success':false,'message':'error...'}");
	    }    
	}
	
	public void init() throws ServletException {
	    
		//初始化上传的路径及临时文件路径
		
		uploadPath=getServletContext().getRealPath("/attachFiles/");
		
	    File uploadPathFile=new File(uploadPath);
	    if(!uploadPathFile.exists()){
	    	uploadPathFile.mkdirs();
	    }
	    tempPath=uploadPath+"/temp";
	    
	    File tempPathFile=new File(tempPath); 
	    if(!tempPathFile.exists()){
	    	tempPathFile.mkdirs();
	    }
	}
	
	
}
